package mqtt

import (
	"gitee.com/injoyai/goutil/crypt/tls"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"time"
)

type Msg mqtt.Message

func WithAliyun(op *OptionAliyun) (o *Option, topicPrefix string) {
	clientID := op.GroupID + "@@@" + op.ClientID
	return &Option{
		BrokerURL: op.BrokerURL,
		ClientID:  clientID,
		Qos:       op.Qos,
		Retained:  op.Retained,
		Username:  "Signature|" + op.AccessKey + "|" + op.InstanceID,
		Password:  HMACSHA1(op.SecretKey, clientID),
		Handler:   op.Handler,
		Timeout:   op.Timeout,
		Debug:     op.Debug,
	}, op.Topic + "/p2p/" + op.GroupID + "@@@"
}

// OptionAliyun 选项
type OptionAliyun struct {
	Model      int             //可选,0是通用mqtt,1是阿里云mqtt
	InstanceID string          //可选
	BrokerURL  string          //必选
	AccessKey  string          //可选
	SecretKey  string          //可选
	Topic      string          //可选,阿里云(必选),其他类型无效
	ClientID   string          //必选,本机Topic地址
	GroupID    string          //必选
	Qos        byte            //可选
	Retained   bool            //可选
	Handler    func(Msg) error //可选,消息处理
	Timeout    time.Duration   //必选,超时时间
	Debug      bool            //可选,调试模式,打印日志
	KeepAlive  time.Duration   //心跳时间
}

// Option 配置
type Option struct {
	BrokerURL string          //必选,不要忘记 tcp://
	ClientID  string          //必选,服务器Topic地址
	Qos       byte            //可选
	Retained  bool            //可选
	Username  string          //用户名
	Password  string          //密码
	Handler   func(Msg) error //消息处理
	Timeout   time.Duration   //超时时间
	Debug     bool            //调试模式,打印日志
	KeepAlive time.Duration   //心跳时间

	TLS       bool
	TLSOption tls.Config
}

//接受收到数据
func (this *Option) handler(c mqtt.Client, msg mqtt.Message) {
	//捉获异常
	defer stack()
	//接受到的数据
	bs := msg.Payload()
	//打印日志
	if this.Debug {
		log.Println("[接收]", string(bs))
	}
	//处理消息
	if this.Handler != nil {
		if err := this.Handler(msg); err != nil {
			log.Println("[错误]", err)
		}
	} else {
		msg.Ack()
	}
}
